package com.yun.many.auth.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yun.many.auth.dao.entity.Resource;
import com.yun.many.auth.dao.service.IResourceRepository;
import com.yun.many.auth.model.req.MenuEditReq;
import com.yun.many.auth.model.req.MenuQueryReq;
import com.yun.many.auth.model.resp.MenuVo;
import com.yun.many.auth.model.translator.MenuTranslator;
import com.yun.many.auth.service.IMenuService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class MenuServiceImpl implements IMenuService {

    private final MenuTranslator menuTranslator;
    private final IResourceRepository resourceRepository;

    @Override
    public Page<MenuVo> pageMenu(MenuQueryReq req) {
        Page<Resource> resourcePage = resourceRepository.pageMenu(req);
        Page<MenuVo> resultPage = new Page<>(req.getCurrent(), req.getSize(), resourcePage.getTotal());
        if (resourcePage.getTotal() == 0) {
            return resultPage;
        }

        List<Resource> records = resourcePage.getRecords();
        List<MenuVo> menuVoList = records.stream().map(menuTranslator::toVo).collect(Collectors.toList());
        resultPage.setRecords(menuVoList);
        return resultPage;
    }

    @Override
    public Boolean save(MenuEditReq req) {
        Resource entity = menuTranslator.toEntity(req);
        return resourceRepository.saveOrUpdate(entity);
    }

    @Override
    public Boolean delete(MenuQueryReq req) {
        List<Long> ids = req.getIds();
        if (CollectionUtils.isEmpty(ids)) {
            log.warn("IUserService.delete ids is empty");
            return true;
        }
        return resourceRepository.removeByIds(ids);
    }

    @Override
    public Boolean frozen(MenuEditReq req) {
        return null;
    }
}
